package com.autonavi.yunda.yunji.service;

import com.autonavi.yunda.yunji.core.model.condition.HealthCheckLogQueryCondition;
import com.autonavi.yunda.yunji.core.model.dto.EngineHealthCheckDTO;
import com.autonavi.yunda.yunji.core.model.dto.HealthCheckLogDTO;
import com.autonavi.yunda.yunji.core.model.dto.InterfaceConfigDTO;
import com.autonavi.yunda.yunji.core.model.mappers.EngineHealthCheckMapper;
import com.autonavi.yunda.yunji.core.model.mappers.HealthCheckLogMapper;
import com.autonavi.yunda.yunji.core.model.mappers.InterfaceConfigMapper;
import com.autonavi.yunda.yunji.core.vo.response.PageVO;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author sunzhenbang
 */
@Service
public class EngineHealthCheckService {
    @Resource
    EngineHealthCheckMapper engineHealthCheckMapper;
    @Resource
    HealthCheckLogMapper healthCheckLogMapper;
    @Resource
    InterfaceConfigMapper interfaceConfigMapper;

    public List<Long> selectAllId(Integer open) {
        return engineHealthCheckMapper.selectAllId(open);
    }

    public int add(EngineHealthCheckDTO toAddDTO) {
        return engineHealthCheckMapper.insert(toAddDTO);
    }

    public void addErrorLog(HealthCheckLogDTO dto) {
        healthCheckLogMapper.insert(dto);
    }

    public void update(EngineHealthCheckDTO engineHealthCheckDTO) {
        engineHealthCheckMapper.updateById(engineHealthCheckDTO);
    }

    public List<EngineHealthCheckDTO> findByInterfaceId(Long interfaceId) {
        return engineHealthCheckMapper.selectList(new QueryWrapper<EngineHealthCheckDTO>().eq("interface_id", interfaceId));
    }

    public EngineHealthCheckDTO findById(Long id) {
        return engineHealthCheckMapper.selectOne(new QueryWrapper<EngineHealthCheckDTO>().eq("id", id));
    }

    public PageVO<HealthCheckLogDTO> listHealthLog(HealthCheckLogQueryCondition condition) {
        Page<HealthCheckLogDTO> page = new Page<>(condition.getPageNo(), condition.getPageSize());
        QueryWrapper<InterfaceConfigDTO> queryWrapper = new QueryWrapper<>();
        queryWrapper.select("id");
        queryWrapper.eq("project_id", condition.getProjectId());
        List<Long> interfaceIds = interfaceConfigMapper.selectList(queryWrapper).stream().map(InterfaceConfigDTO::getId).collect(Collectors.toList());
        if (interfaceIds.isEmpty()) {
            return PageVO.empty();
        }
        condition.setInterfaceIdList(interfaceIds);
        healthCheckLogMapper.selectPage(page, condition.fetchQueryWrapper());
        return new PageVO<>(page.getRecords(), page.getTotal());
    }
}
